/**
 * Copyright (c) 2015 https://github.com/howiefh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.tyijian.admin.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTSigner.Options;
import com.tyijian.admin.core.exceptionHandle.RestException;
import com.tyijian.admin.entity.SysUser;
import com.tyijian.admin.service.UserService;
import com.tyijian.springside.core.Constant;
import com.tyijian.springside.core.StatusConstant;
import com.tyijian.springside.core.utils.MediaTypes;

/**
 * 登录controller
 * 
 */
@RestController
@RequestMapping("/login")
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	public Map<String, Object> login(@RequestBody SysUser u) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		String loginname = u.getLoginname();
		String password = u.getPassword();
		if (loginname == null) {
			throw new RestException(HttpStatus.BAD_REQUEST, "参数输入有误");
		}
		SysUser user = userService.findByLoginname(loginname);

		if (user == null) {
			throw new RestException(HttpStatus.NOT_FOUND, "该用户不存在");
		}

		if (!StatusConstant.USER_STATUS.equals(user.getStatus())) {
			throw new RestException(HttpStatus.LOCKED, "该用户已冻结，请联系管理员");
		}

		if (!userService.passwordsMatch(user, password)) {
			throw new RestException(HttpStatus.UNAUTHORIZED, "用户或密码不正确");
		}

		JWTSigner signer = new JWTSigner(Constant.SECRET);
		Options options = new Options();
        options.setExpirySeconds(24 * 60 * 60); //设置token 24小时后过期
		
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put("userId", user.getId());
		claims.put("loginName", user.getLoginname());
		claims.put("expires_in", System.currentTimeMillis()); // token生成时间
		String token = signer.sign(claims,options);
		user.setToken(token);
		
		map.put("access_token", token);
		map.put("user", user);
		
		userService.setTokenCache("UserCache:"+user.getLoginname(),user,24 * 60 * 60L); //缓存user
		
		return map;
	}
	
}
